import 'package:flutter/material.dart' hide ReorderableListView;
import 'dart:io';
import '../utils/common_utils.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'custom_reorderable_listView.dart';
import 'fileimage_ex.dart';

class DraggableImagePickerWidget extends StatelessWidget {
  List items;
  Function(dynamic item) onDelete;
  Function(File) onAdd;
  Function(int oldIndex, int newIndex) onReorder;

  DraggableImagePickerWidget(
      this.items, this.onDelete, this.onAdd, this.onReorder);

  Widget _insetWidget(BuildContext context) => InkWell(
        key: Key('insert'),
        child: Container(
          width: 100,
          height: 100,
          color: Color(0xffF7F7F7),
          child: Center(
            child: Icon(
              Icons.add,
              color: Color(0xff989898),
            ),
          ),
        ),
        onTap: () async {
          File imgFile = await CommonUtils.showImagePicker(context);
          if (imgFile == null) {
            return;
          }
          onAdd(imgFile);
        },
      );

  Widget _imgWidget(BuildContext context, var item) {
    return InkWell(
      key: Key(item.toString()),
      child: Container(
        margin: EdgeInsets.only(left: 6, right: 6),
        child: item.runtimeType.toString() == '_File'
            ? Image(
                image: FileImageEx(item),
                width: 100,
                height: 100,
                fit: BoxFit.fill,
              )
            : CachedNetworkImage(
                imageUrl: item,
                fit: BoxFit.contain,
                width: 100,
                height: 100,
              ),
      ),
      onTap: () async {
        var res = await CommonUtils.showActionSheet(context, button: ['删除']);
        if (res == 0) onDelete(item);
      },
    );
  }

  Widget _body(BuildContext context) {
    if (items.length == 0)
      return Row(
        children: <Widget>[_insetWidget(context)],
      );
    if (items.length == 1)
      return Row(
        children: <Widget>[
          _imgWidget(context, items[0]),
          Padding(padding: EdgeInsets.only(left: 6)),
          _insetWidget(context),
        ],
      );
    List<Widget> _list = items.map<Widget>((var item) {
      return _imgWidget(context, item);
    }).toList();
    return ReorderableListView(
      scrollDirection: Axis.horizontal,
      onReorder: (int oldIndex, int newIndex) => onReorder(oldIndex, newIndex),
      children: _list,
      header: _insetWidget(context),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 12),
      height: 100,
      width: double.infinity,
      child: _body(context),
    );
  }
}
